import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import { responseData } from '../common/response.handle';
import { IPaginationOptions } from '../utils/types/pagination-options';

@Injectable()
export class RoleService {
	constructor(
		@InjectRepository(Role)
		private roleRepository: Repository<Role>,
	) {}

	async create(createRoleDto: CreateRoleDto, userId: string) {
		await this.roleRepository.save(
			this.roleRepository.create({
				...createRoleDto,
				creatorId: userId,
			}),
		);
		return responseData(null, '创建角色成功');
	}

	async findAll() {
		const roles = await this.roleRepository.find();
		return responseData(roles, '查询全部角色成功');
	}

	async findListByPage(paginationOptions: IPaginationOptions) {
		const [roles, total] = await this.roleRepository
			.createQueryBuilder('permissions')
			.leftJoinAndSelect('permissions.user', 'user')
			.where('name LIKE :name OR description LIKE :description', {
				name: `%${paginationOptions.keyword}%`,
				description: `%${paginationOptions.keyword}%`,
			})
			.skip((paginationOptions.pageNum - 1) * paginationOptions.pageSize)
			.take(paginationOptions.pageSize)
			.getManyAndCount();
		return responseData(
			{
				list: roles.map((item) => {
					const pms = item;
					const creator = pms.user.nickname;
					delete pms.user;
					return {
						...pms,
						creator,
					};
				}),
				total,
				totalPages: Math.ceil(total / paginationOptions.pageSize),
			},
			'查询权限列表成功',
		);
	}

	findOne(id: number) {
		return `This action returns a #${id} role`;
	}

	async update(id: number, updateRoleDto: UpdateRoleDto) {
		await this.roleRepository.update(id, updateRoleDto);
		return responseData(null, '更新角色成功');
	}

	async remove(id: number) {
		await this.roleRepository.delete(id);
		return responseData(null, '删除角色成功');
	}
}
